<template>
  <div>
    <div>
    <el-row :gutter="20">
            <el-col :span="1.5"><el-button size="small" @click="addButton = true">轮播图片上传</el-button></el-col>
            <!-- <el-col :span="1"><el-button size="small" @click="getfrontdeskuser()">搜索</el-button></el-col> -->
            <el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
            <el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
        </el-row> 
        <div style="height:30px ;width: 100%;background:#f5f5f5; position: relative; top: 9px;">
        </div>
        <!-- 全查 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="img" label="轮播图片" align="center">
        <template slot-scope="scope">
        <el-image style="height: 100px" :src="'http://101.43.223.224:8765/image/getImageById?id=' + scope.row.img">
        </el-image>
        </template>
        </el-table-column>
        <el-table-column prop="carouselName" label="图片信息" align="center">
        </el-table-column>
        <el-table-column prop="sortNumber" label="排序号"  align="center">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center">
        </el-table-column>
        <el-table-column prop="updateTime" label="修改时间"  align="center">
        </el-table-column>
        <el-table-column label="轮播图状态"  align="center">
        <template slot-scope="scope">
                <el-switch v-model="scope.row.carouselStatus"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="0"
                    :inactive-value="1"
                    @change=Releasecarousel(scope.row)>
                </el-switch>
            </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
        <template slot-scope="scope">
        <el-button @click="update(scope.row)">修改</el-button>
        <!-- <el-button @click="deletecarousel(scope.row.id)" size="mini" v-if="scope.row.carouselStatus==0">禁用</el-button>
        <el-button @click="Releasecarousel(scope.row.id)" size="mini" v-else>启用</el-button> -->
        <el-button @click="deletedata(scope.row)" size="mini">删除</el-button>
        </template> 
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <el-pagination
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pages.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pages.total"
      :current-page.sync="pages.pageNum"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      align="center"
      width="100%"
      >
    </el-pagination>
    <!-- 上传图片表单 -->
        <el-dialog :visible.sync="addButton" width="30%" style="text-align: left">
        <el-form stripe style="width: 100%; text-align: left" :model="addForm" ref="addForm">
          <el-form-item>
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px">图片</span>
            <el-upload class="avatar-uploader" action="" list-type="picture-card" style="margin-top: -40px; margin-left: 100px;width:30%" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img height="150" v-if="carouselImg" :src="carouselImg" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

        <el-form-item>
        <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
        <span style="margin-left: 20px">图片信息：</span>
        <el-input v-model="addForm.carouselName" placeholder="输入图片信息" style="width: 130px;"></el-input>
        </el-form-item>
        
        <el-form-item>
        <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
        <span style="margin-left: 20px">排序号：</span>
        <template>
          <el-input-number v-model="addForm.sortNumber" @change="handleChange" :min="1" :max="20" type="number" label="描述文字"></el-input-number>
        </template>
        </el-form-item>

        </el-form>
        <el-button style="background-color: rgb(234, 244, 255); color: rgb(96, 169, 255)" @click="addcarousel('addForm')">确 定</el-button>
        <el-button @click="addButton = false" style="background-color: rgb(234, 244, 255); color: rgb(96, 169, 255)">取 消</el-button>
      </el-dialog>

      <!-- 修改图片表单 -->
        <el-dialog :visible.sync="updateButton" width="30%" style="text-align: left">
        <el-form stripe style="width: 100%; text-align: left" :model="updateForm" ref="updateForm">
          <el-form-item>
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px">轮播图片：</span>
            <el-upload class="avatar-uploader" action="" style="margin-top: -40px; margin-left: 100px" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUploadup">
              <img height="210" v-if="carouselupImg" :src="carouselupImg" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

        <el-form-item>
        <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
        <span style="margin-left: 20px">图片信息：</span>
        <el-input v-model="updateForm.carouselName" placeholder="输入图片信息" style="width: 130px;"></el-input>
        </el-form-item>
        
        <el-form-item>
        <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
        <span style="margin-left: 20px">排序号：</span>
        <template>
          <el-input-number v-model="updateForm.sortNumber" @change="handleChange" :min="1" :max="20" label="描述文字"></el-input-number>
        </template>
        </el-form-item>

        </el-form>
        <el-button style="background-color: rgb(234, 244, 255); color: rgb(96, 169, 255)" @click="updatecarousel('updateForm')">确 定</el-button>
        <el-button @click="updateButton = false" style="background-color: rgb(234, 244, 255); color: rgb(96, 169, 255)">取 消</el-button>
      </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [],
      addButton:false,
      updateButton:false,
      addForm:{
        sortNumber:1
      },
      updateForm:{
        sortNumber:1
      },
      carouselImg:'',
      carouselupImg:'',
      imgCarousel:'',
      imgupCarousel:'',
      pages: {
        //分页参数
        total: 0, // 数据总条数
        pageNum: 1, // 当前页
        pageSize: 5, // 每页条数
      },
    };
  },
   mounted () {
    this.getcarousel()
    // this.$router.afterEach(to => {
    //   // 在路由跳转完成后执行的方法
    //   if (to.path === '/home') {
    //     this.methodToExecuteAfterNavigation();
    //   }
    // });
  },
  methods: {
    // methodToExecuteAfterNavigation() {
    //   // 路由跳转完成后执行的方法
    //   window.location.reload(); //监测到路由发生跳转时刷新一次页面
    // },
    getcarousel() {
      // 查询所需数据(全查)
      this.$axios
        .get("/Carousel/getCarousel", {
          params: {
            pageNum: this.pages.pageNum, // 当前页
            pageSize: this.pages.pageSize, // 每条页数
          },
        })
        .then((res) => {
          if (res.data.code=200) {
            //
            this.tableData = res.data.data.content;
            this.pages.total = res.data.data.totalSize;   
          }
          this.loading = false; // 加载圈绑定
        })
        .catch((err) => {
          // this.myMessage('error', err),
        });
    },
    
    addcarousel(addForm){
      this.$refs[addForm].validate((valid) =>{
        if (valid) {
          const formData = new FormData()
            formData.set("carouselName", this.addForm.carouselName);
            formData.set("sortNumber", this.addForm.sortNumber);
          // 轮播图片
          if (this.imgCarousel) {
            formData.set('file', this.imgCarousel, this.imgCarousel.name)
          }
          this.$axios.post("/Carousel/addCarousel", formData).then((res) => {
            if (res.data) {
              this.$message.success('上传成功')
              //清空表单
              this.addForm={}
              this.carouselImg = ''
              // 关闭窗口
              this.addButton = false 
              //刷新
              this.getcarousel()
            } else {
              this.$message.error('warning', res.data.code)
            }
          }).catch((err) => {
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    update(row){
      this.updateButton=true,
      this.updateForm = JSON.parse(JSON.stringify(row))
      this.carouselupImg = 'http://101.43.223.224:8765/image/getImageById?id=' + row.img;
    },

    updatecarousel(){
          const formDatas = new FormData()
            formDatas.set("id", this.updateForm.id)
            formDatas.set("carouselName", this.updateForm.carouselName);
            formDatas.set("sortNumber", this.updateForm.sortNumber);
          // 轮播图片
          if (this.imgupCarousel) {
            formDatas.set('file', this.imgupCarousel, this.imgupCarousel.name)
          }
          this.$axios.post("/Carousel/updateCarousel", formDatas).then((res) => {
            if (res.data) {
              this.$message.success('修改成功')
              //清空表单
              this.updateForm={}
              // 关闭窗口
              this.updateButton = false 
              //刷新
              this.getcarousel()
            } else {
              this.$message.error('warning', res.data.code)
            }
          }).catch((err) => {
            console.log(err)
          })
    }, 
  // 图片格式验证
  beforeAvatarUpload(file) {
  // 上传图片格式
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isJPG && !isPNG) {
    this.$message.error('上传图片只能是JPG/PNG格式！');
    return false;
  }
  if (!isLt2M) {
    this.$message.error('上传图片大小不能超过2MB！');
    return false;
  }
  // 校验长宽比例
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.src = URL.createObjectURL(file);
    image.onload = () => {
      const width = image.width;
      const height = image.height;
      const aspectRatio = width / height;
      const targetRatio = 16 / 9;
      if (Math.abs(aspectRatio - targetRatio) > 0.05) {
        this.$message.error('上传图片长宽比例应为16:9左右');
        reject();
      } else {
        this.imgCarousel = file;
        this.carouselImg = URL.createObjectURL(file);
        resolve();
      }
    };
  });
},
// 图片格式验证
  beforeAvatarUploadup(file) {
  // 上传图片格式
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isJPG && !isPNG) {
    this.$message.error('上传图片只能是JPG/PNG格式！');
    return false;
  }
  if (!isLt2M) {
    this.$message.error('上传图片大小不能超过2MB！');
    return false;
  }
  // 校验长宽比例
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.src = URL.createObjectURL(file);
    image.onload = () => {
      const width = image.width;
      const height = image.height;
      const aspectRatio = width / height;
      const targetRatio = 16 / 9;
      if (Math.abs(aspectRatio - targetRatio) > 0.01) {
        this.$message.error('上传图片长宽比例应为16:9！');
        reject();
      } else {
        this.imgupCarousel = file;
        this.carouselupImg = URL.createObjectURL(file);
        resolve();
      }
    };
  });
},
    // 轮播图启用方法
    Releasecarousel(row){
        const forms = new FormData();
        forms.set("id", row.id);
        forms.set("carouselStatus", row.carouselStatus);
        this.$axios
          .post("/Carousel/ReleaseCarousel",forms)
          .then((res) => {
            if ((res.data.data.code == 200)) {
              this.myMessage("success", res.data.data.data);
              this.getcarousel();
            } else {
              this.myMessage("wanging", res.data.data.data);
            }
          })
          .catch(() => {
            this.myMessage("info", "操作有误");
          });
    },
    // 轮播图删除方法
    deletedata(row){
      this.$confirm("此操作将永久删除该文件,是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
        }).then(()=>{
          if(row.carouselStatus == 1){
          const formss = new FormData();
          formss.set("id", row.id);
          this.$axios
            .post("/Carousel/deleteData",formss)
            .then((res) => {
              if ((res.data.data.code == 200)) {
                this.myMessage("success", "删除成功");
                this.getcarousel();
              } else {
                this.myMessage("wanging", "删除失败");
              }
            })
            .catch(() => {
              this.myMessage("info", "删除有误");
          });
          }else {
            this.myMessage("info", "图片正在使用中");
          }
        }).catch(() => {
            this.myMessage("info", "删除已取消");
          });
        
    },

    // 分页插件方法
    handleSizeChange(val) {
      this.pages.pageSize = val;
      this.getcarousel();
    },
    handleCurrentChange(val) {
      this.pages.pageNum = val;
      this.getcarousel();
    },
    myMessage(type, message) {
      this.$message({
        message: message,
        type: type,
      });
    },
    handleAvatarSuccess() {
    },
    handleChange(value) {
      console.log(value);
    }
  }
};
</script>

<style>
.el-button:focus, .el-button:hover {
    color: #19CAAD;
    border-color: #19CAAD;
    background-color: #fafafa;
}
.el-upload--picture-card {
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    width: 270px;
    height: 152px;
    cursor: pointer;
    line-height: 146px;
    vertical-align: top;
}
</style>